package com.smartrobot.smartrobot.DB;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.pojo.getFriendListPojo;
import com.smartrobot.smartrobot.pojo.NewFriendPojo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by yeluojun on 2015/1/19.
 */
public class NewFriendSqlHelper {

    /* 日志的标志 */
    private static final String TAG = "sqlite for new friend";

    /*创建新的朋友的数据库*/
    public static final  String CREATE_NEW_FRIEND_DB = "create table new_friend( id INTEGER primary key autoincrement ," +
            "userId varchar(255) ,headImg varchar(255) ,name varchar(255),nickname varchar(255)" +
            ",sex varchar(255),role varchar(12),userAccount varchar(255),msg varchar(255),status varchar(255),editTime varchar(255))";


    /*数据库的名字*/
    private static  String DB_NAME = "SmartRobot";

    /*表名字*/
    public static  final String TABLE_NAME = "new_friend";

    /*数据库版本*/
    static final int DATABASE_VERSION = 1;


    /*数据库的字段*/
    public static final String USER_ID = "userId";
    public static final String HEAD_IMG = "headImg";
    public static final String USER_NAME = "name";
    public static final String NICKNAME = "nickname";
    public static final String SEX = "sex";
    public static final String ROLE = "role";
    public static final String USER_ACCOUNT = "userAccount";
    public static final String MSG = "msg";
    public static final String STATUS = "status";
    public static final String EDIT_TIME = "editTime";


    /*数据标志*/
    public static final String UN_NOK = "未验证";
    public static final String PASS = "已通过";
    public static final String UN_PASS = "已拒绝";






    Context context;

    SQLiteDatabase db;

    DatabaseHelper DBHelper;


    public NewFriendSqlHelper(Context cxt,String db_name)
    {
        this.context = cxt;
        DB_NAME = db_name+"_"+TABLE_NAME;
        DBHelper = new DatabaseHelper(context);
    }



    private static class DatabaseHelper extends SQLiteOpenHelper
    {

        DatabaseHelper(Context context)
        {
            super(context, DB_NAME, null, DATABASE_VERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {

            try
            {
                db.execSQL(CREATE_NEW_FRIEND_DB);
            }
            catch(SQLException e)
            {

                Log.w("=======创建数据库失败=======",e.toString());
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.e(TAG, "Upgrading database from version " + oldVersion + "to " +
                    newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME );
//            onCreate(db);
        }
    }


    public NewFriendSqlHelper open() throws SQLException
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    public void close()
    {
        DBHelper.close();
    }


    /*插入数据库*/
    public synchronized long insertNewFriend(getFriendListPojo pojo,String msg)
    {
        Date date = new Date();

        ContentValues initialValues = new ContentValues();
        initialValues.put(USER_ID, pojo.getUserId());
        initialValues.put(HEAD_IMG, pojo.getHeadImg());
        initialValues.put(USER_NAME, pojo.getReName());
        initialValues.put(NICKNAME, pojo.getName());
        initialValues.put(SEX, pojo.getSex());
        initialValues.put(ROLE, pojo.getRole());
        initialValues.put(USER_ACCOUNT, pojo.getUserAccount());
        initialValues.put(MSG,msg);
        initialValues.put(STATUS,UN_NOK);
        initialValues.put(EDIT_TIME, date.getTime()+"");


        return db.insert(TABLE_NAME, null, initialValues);

    }


    /*删除数据*/
    public synchronized boolean deleteFromNewFriend(String userId){
        try{
          db.delete(TABLE_NAME, USER_ID + "=" +userId, null) ;
            return true;
        }catch (Exception e){
            LogToSd.log_init();
            LogToSd.error(e.toString());
            return false;
        }

    }



    /*更新数据---状态*/
    public synchronized boolean  updateFromNewFriend(String status,String userId){
        try{
            ContentValues args = new ContentValues();
            args.put(STATUS, status);
             db.update(TABLE_NAME, args, USER_ID + "=" +userId, null) ;
            return true;
        }catch(Exception e){
            LogToSd.log_init();
            LogToSd.error(e.toString());
            return false;
        }

    }

    /*更新数据----全部*/
    public synchronized boolean updateAllFromNewFriend(getFriendListPojo pojo, String msg){
        try{

            ContentValues initialValues = new ContentValues();
            initialValues.put(HEAD_IMG, pojo.getHeadImg());
            initialValues.put(USER_NAME, pojo.getReName());
            initialValues.put(NICKNAME, pojo.getName());
            initialValues.put(SEX, pojo.getSex());
            initialValues.put(ROLE, pojo.getRole());
            initialValues.put(USER_ACCOUNT, pojo.getUserAccount());
            initialValues.put(MSG,msg);
            initialValues.put(STATUS,UN_NOK);
            String[] args = {String.valueOf(pojo.getUserId())};
            db.update(TABLE_NAME, initialValues, "userId=?",args);
            return true;
        }catch (Exception e){
            LogToSd.log_init();
            LogToSd.error(e.toString());
            return false;
        }

    }

    /*查找数据--显示全部*/
    public List<NewFriendPojo> searchFromNewFriend(){

        List<NewFriendPojo> list  = new ArrayList<NewFriendPojo>();
        try{

            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " order by editTime desc",null);
            while(cursor.moveToNext()){
                NewFriendPojo pojo = new NewFriendPojo();
                String userId = cursor.getString(cursor.getColumnIndex(USER_ID));
                String username = cursor.getString(cursor.getColumnIndex(USER_NAME));
                String nickname = cursor.getString(cursor.getColumnIndex(NICKNAME));
                String headImg = cursor.getString(cursor.getColumnIndex(HEAD_IMG));
                String userAccount = cursor.getString(cursor.getColumnIndex(USER_ACCOUNT));
                String sex = cursor.getString(cursor.getColumnIndex(SEX));
                String role = cursor.getString(cursor.getColumnIndex(ROLE));
                String msg = cursor.getString(cursor.getColumnIndex(MSG));
                String status = cursor.getString(cursor.getColumnIndex(STATUS));

                pojo.setUserId(userId);
                pojo.setReName(username);
                pojo.setHeadImg(headImg);
                pojo.setUserAccount(userAccount);
                pojo.setRole(role);
                pojo.setSex(sex);
                pojo.setMsg(msg);
                pojo.setName(nickname);
                pojo.setStatus(status);

                list.add(pojo);

            }
            cursor.close();
        }catch (SQLiteException e){

            LogToSd.log_init();
            LogToSd.error(e.toString());
        }
        return list;
    }



    /*判断数据是否存在*/
    public Boolean ifExist(String userId){
        Boolean exist = false;
        String[] args = {String.valueOf(userId)};
        Cursor cursor = db.rawQuery("select userId from " + TABLE_NAME + " where userId = ? ",args);
        int count = cursor.getCount();
        if (count>0){
            exist = true;
        }
        cursor.close();
        return exist;
    }
}
